package com.scy.handler;

import com.alibaba.fastjson.JSON;
import com.scy.common.Result;
import com.scy.entity.User;
import com.scy.service.LoginService;
import com.scy.service.UserService;
import com.scy.utils.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 本类用来演示
 *
 * @author wwh
 * @date 2024/7/5 13:28 $
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    LoginService loginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//        获取token
        String token = request.getHeader("Authorization");


        //如果没有token,说明未登陆过
        if (token == null){
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(Result.fail(1003,"未登录")));
            return false;
        }
        //对token进行验证,空==>签名验证==>redis
        User user = loginService.checkToken(token);

        //看解析后的对象,是否存在
        if (user == null){
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(Result.fail(1003,"未登录")));
            return false;
        }

        /*将数据存入线程共享变量中*/
        UserThreadLocal.put(user);

        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
